package dapps.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jasig.cas.client.authentication.AttributePrincipal;
import org.jasig.cas.client.validation.AssertionImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.Authentication;
import org.springframework.security.context.SecurityContextHolder;
import org.springframework.security.providers.UsernamePasswordAuthenticationToken;
import org.springframework.security.ui.WebAuthenticationDetails;
import org.springframework.security.ui.webapp.AuthenticationProcessingFilter;

public final class loginfilter implements Filter {

    private FilterConfig config = null;
    private String username = "";
    private String password = "123";
	@Autowired
	private org.springframework.security.AuthenticationManager authenticationManager;
    //~ Methods ================================================================
	
    /**
     * Initialize controller values of filter.
     */
    public void init(FilterConfig config) {
        this.setConfig(config);
        password = config.getInitParameter("password");
    }
    public void doFilter(ServletRequest req, ServletResponse resp,
                         FilterChain chain)
                  throws IOException, ServletException {
    	
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        if(request.getSession().getAttribute("_const_cas_assertion_")==null){
			response.sendRedirect(request.getContextPath()+"/j_spring_security_logout");
			return;
		}
        AssertionImpl assertion = (AssertionImpl) request.getSession().getAttribute("_const_cas_assertion_");
		AttributePrincipal ap = assertion.getPrincipal();
		if(ap==null){
			response.sendRedirect(request.getContextPath()+"/j_spring_security_logout");
			return;
		}else{
			username = ap.getName();
		}
					
		if (request.getSession().getAttribute(AuthenticationProcessingFilter.SPRING_SECURITY_LAST_USERNAME_KEY)==null||
			!username.equals((String)request.getSession().getAttribute(AuthenticationProcessingFilter.SPRING_SECURITY_LAST_USERNAME_KEY))) {
			
			UsernamePasswordAuthenticationToken authen = new UsernamePasswordAuthenticationToken(
					username, password);
			// 保存用户名到 session里
			request.getSession().setAttribute(
							AuthenticationProcessingFilter.SPRING_SECURITY_LAST_USERNAME_KEY,
							username);
			WebAuthenticationDetails webdetails = new WebAuthenticationDetails(request);
			// 注意:这里 setDetails的对象一定要是WebAuthenticationDetails
			authen.setDetails(webdetails);
			// 这里验证不通过会返回null对象

			Authentication auth1 = authenticationManager.authenticate(authen);
			SecurityContextHolder.getContext().setAuthentication(auth1);
			System.out.println("认证是否通过: " + auth1.isAuthenticated());
		}
		
		
        chain.doFilter(request, response);
    }

	public org.springframework.security.AuthenticationManager getAuthenticationManager() {
		return authenticationManager;
	}

	public void setAuthenticationManager(
			org.springframework.security.AuthenticationManager authenticationManager) {
		this.authenticationManager = authenticationManager;
	}

    /**
     * destroy any instance values other than config *
     */
    public void destroy() {
    	setConfig(null);
    }
	public void setConfig(FilterConfig config) {
		this.config = config;
	}
	public FilterConfig getConfig() {
		return config;
	}
}